/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Enum.SearchGeneralEnum;
import dao.ChiTietHoaDonDAO;
import dao.HoaDonDAO;
import dao.NguoiDungDAO;
import dao.SanPhamCuaHangDAO;
import dao.TrangThaiDonHangDAO;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.log4j.Logger;
import pojo.ChiTietHoaDon;
import pojo.HoaDon;
import pojo.NguoiDung;
import pojo.SanPhamCuaHang;
import pojo.TrangThaiDonHang;

/**
 *
 * @author softviet
 */
public class HoaDonGUI extends javax.swing.JDialog {

    /**
     * Creates new form HoaDonGUI
     */
    private HoaDon hoaDon;
    private JErrorProvider errorProvider;
    private static Logger logger = Logger.getLogger(HoaDonGUI.class);
    private NguoiDung selectedKhachHang;
    private SanPhamCuaHang selectedSanPhamCuaHang;
    private ArrayList<ChiTietHoaDon> chiTietHoaDons;
    private MyEventListener ButtonLuuClickedListener;
    private List<TrangThaiDonHang> trangThaiDonHangs;
    private HoaDon oldHoaDon;

    public HoaDonGUI(java.awt.Frame parent, boolean modal, HoaDon hoaDon) throws Exception {
        super(parent, modal);
        initComponents();
        errorProvider = new JErrorProvider();
        this.hoaDon = hoaDon;
        oldHoaDon = new HoaDon();
        oldHoaDon.setTongTien(hoaDon.getTongTien());
        oldHoaDon.setTrangThaiDonHang(hoaDon.getTrangThaiDonHang());
        if (this.hoaDon.getId() != 0) {
            this.setTitle("Chi tiết hoá đơn");
            txtMaKhachHang.setEditable(false);
            dtNgayLapHoaDon.setEditable(false);
            btnSearchKhachHang.setEnabled(false);
        } else {
            this.setTitle("Lập hoá đơn");
            txtMaKhachHang.setEditable(true);
            dtNgayLapHoaDon.setEditable(true);
            btnSearchKhachHang.setEnabled(true);
        }
        SetTabOrder();
        FormatControls();
        AutoLoad();
    }

    private void SetTabOrder() {
        IndexedFocusTraversalPolicy indexedFocusTraversalPolicy = new IndexedFocusTraversalPolicy();
        indexedFocusTraversalPolicy.addIndexedComponents(new Component[]{txtMaKhachHang, btnSearchKhachHang, txtTenKhachHang, dtNgayLapHoaDon, txtTongTien, txtMaSanPhamCuaHang, btnSearchSanPham, txtTenSanPham, txtDonGia, txtSoLuongTon, txtSoLuongDat, txtTongTienChiTiet, btnThem, btnXoa, btnClear, btnLuu, btnThoat});
        setFocusTraversalPolicy(indexedFocusTraversalPolicy);
    }

    private void FormatControls() {
        Utility.FormatNumberStringTextfield(txtMaKhachHang);
        Utility.FormatDecimalTextfield(txtTongTien);
        Utility.FormatNumberStringTextfield(txtMaSanPhamCuaHang);
        Utility.FormatDecimalTextfield(txtDonGia);
        Utility.FormatNumberStringTextfield(txtSoLuongDat);
        Utility.FormatDecimalTextfield(txtTongTienChiTiet);
    }

    private void AutoLoad() throws Exception {
        if (hoaDon.getNgayLapHoaDon() == null) {
            dtNgayLapHoaDon.setDate(new Date());
        }
        txtSoLuongDat.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                CalculateTongTienChiTiet();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                CalculateTongTienChiTiet();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                CalculateTongTienChiTiet();
            }
        });

        if (hoaDon.getId() == 0) {
            chiTietHoaDons = new ArrayList<>();
        } else {
            setSelectedKhachHang(hoaDon.getNguoiDung());
            dtNgayLapHoaDon.setDate(hoaDon.getNgayLapHoaDon());
            txtTongTien.setValue(hoaDon.getTongTien());
            chiTietHoaDons = (ArrayList<ChiTietHoaDon>) ChiTietHoaDonDAO.LayDanhSachByHoaDonID(hoaDon.getId());
        }
        Utility.CreateColumnsFromDB(ChiTietHoaDon.class, chiTietHoaDons, tbChiTietHoaDon, new String[]{"Mã sản phẩm cửa hàng", "Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Đã thanh toán"}, new String[]{"id", "idHoaDon"});
        trangThaiDonHangs = (List<TrangThaiDonHang>) TrangThaiDonHangDAO.LayDanhSach(TrangThaiDonHang.class, MainGUI.nguoiDung);
    }

    private void CalculateTongTienChiTiet() {
        if (!txtSoLuongDat.getText().isEmpty() && !txtDonGia.getText().isEmpty()) {
            txtTongTienChiTiet.setValue(((Double) txtDonGia.getValue()) * Integer.parseInt(txtSoLuongDat.getText()));
        } else {
            txtTongTienChiTiet.setValue(null);
        }
    }

    private int CheckDataBeforeThem() {
        int dem = 0;
        errorProvider.clear();
        if (txtMaSanPhamCuaHang.getText().isEmpty()) {
            errorProvider.setError(txtMaSanPhamCuaHang, "required");
            dem++;
        }
        if (txtSoLuongDat.getText().isEmpty()) {
            errorProvider.setError(txtSoLuongDat, "required");
            dem++;
        }
        if (!txtSoLuongDat.getText().isEmpty() && !txtSoLuongTon.getText().isEmpty()) {
            if (Integer.parseInt(txtSoLuongDat.getText()) > Integer.parseInt(txtSoLuongTon.getText())) {
                errorProvider.setError(txtSoLuongDat, "Số lượng đặt không được lớn hơn số lượng tồn");
                dem++;
            }
        }
        return dem;
    }

    private int CheckDataBeforeLuu() {
        int dem = 0;
        errorProvider.clear();
        if (txtMaKhachHang.getText().isEmpty()) {
            errorProvider.setError(txtMaKhachHang, "required");
            dem++;
        }
        if (dtNgayLapHoaDon.getDate() == null) {
            errorProvider.setError(dtNgayLapHoaDon, "required");
            dem++;
        }
        if (chiTietHoaDons.isEmpty() && dem == 0) {
            JOptionPane.showMessageDialog(this, "Xin nhập chi tiết hoá đơn");
            dem++;
        }
        return dem;
    }

    private void CalculateTongTien() {
        Double tongTien = 0.0;
        for (ChiTietHoaDon chiTietHoaDon : chiTietHoaDons) {
            tongTien += chiTietHoaDon.getTongTien();
        }
        txtTongTien.setValue(tongTien == 0 ? null : tongTien);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtTenKhachHang = new javax.swing.JTextField();
        btnSearchKhachHang = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtMaKhachHang = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        dtNgayLapHoaDon = new org.jdesktop.swingx.JXDatePicker();
        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtTenSanPham = new javax.swing.JTextField();
        btnSearchSanPham = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        txtDonGia = new javax.swing.JFormattedTextField();
        jLabel9 = new javax.swing.JLabel();
        txtMaSanPhamCuaHang = new javax.swing.JTextField();
        txtSoLuongTon = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtSoLuongDat = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtTongTienChiTiet = new javax.swing.JFormattedTextField();
        btnThem = new javax.swing.JButton();
        btnXoa = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbChiTietHoaDon = new org.jdesktop.swingx.JXTable();
        btnClear = new javax.swing.JButton();
        btnLuu = new javax.swing.JButton();
        btnThoat = new javax.swing.JButton();
        txtTongTien = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Hoá đơn");
        setResizable(false);

        jLabel2.setText("Tên khách hàng");

        jLabel3.setText("Ngày lập hoá đơn");

        txtTenKhachHang.setEditable(false);

        btnSearchKhachHang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/SearchIconImage.gif"))); // NOI18N
        btnSearchKhachHang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchKhachHangActionPerformed(evt);
            }
        });

        jLabel5.setText("Tổng tiền");

        txtMaKhachHang.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaKhachHangFocusLost(evt);
            }
        });

        jLabel1.setText("Mã khách hàng");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Chi tiết hoá đơn"));

        jLabel6.setText("Mã sản phẩm cửa hàng");

        jLabel7.setText("Tên sản phẩm");

        txtTenSanPham.setEditable(false);

        btnSearchSanPham.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/SearchIconImage.gif"))); // NOI18N
        btnSearchSanPham.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchSanPhamActionPerformed(evt);
            }
        });

        jLabel8.setText("Đơn giá");

        txtDonGia.setEditable(false);

        jLabel9.setText("Số lượng tồn");

        txtMaSanPhamCuaHang.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaSanPhamCuaHangFocusLost(evt);
            }
        });

        txtSoLuongTon.setEditable(false);

        jLabel10.setText("Số lượng đặt");

        jLabel11.setText("Tổng tiền");

        txtTongTienChiTiet.setEditable(false);

        btnThem.setText("Thêm");
        btnThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemActionPerformed(evt);
            }
        });

        btnXoa.setText("Xoá");
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        tbChiTietHoaDon.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tbChiTietHoaDon);

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtTenSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                    .addComponent(txtMaSanPhamCuaHang)
                    .addComponent(txtDonGia))
                .addGap(26, 26, 26)
                .addComponent(btnSearchSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(76, 76, 76)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(jLabel9)
                    .addComponent(jLabel11))
                .addGap(37, 37, 37)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtSoLuongDat, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                    .addComponent(txtSoLuongTon)
                    .addComponent(txtTongTienChiTiet))
                .addGap(28, 28, 28))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnThem)
                .addGap(18, 18, 18)
                .addComponent(btnXoa)
                .addGap(18, 18, 18)
                .addComponent(btnClear)
                .addGap(249, 249, 249))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel9)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel6)
                                .addComponent(txtMaSanPhamCuaHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnSearchSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(txtSoLuongTon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtSoLuongDat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtTongTienChiTiet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnThem)
                    .addComponent(btnXoa)
                    .addComponent(btnClear))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
        );

        btnLuu.setText("Lưu");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        btnThoat.setText("Thoát");
        btnThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThoatActionPerformed(evt);
            }
        });

        txtTongTien.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtTenKhachHang)
                    .addComponent(txtMaKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(btnSearchKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dtNgayLapHoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTongTien, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnLuu)
                .addGap(18, 18, 18)
                .addComponent(btnThoat)
                .addGap(292, 292, 292))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dtNgayLapHoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addComponent(txtTongTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSearchKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtMaKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTenKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLuu)
                    .addComponent(btnThoat))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSearchKhachHangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchKhachHangActionPerformed
        try {
            // TODO add your handling code here:
            DialogGeneralSeach dialogGeneralSeach = new DialogGeneralSeach(null, true, SearchGeneralEnum.KhachHang);
            final int x = (getWidth() - dialogGeneralSeach.getWidth()) + getX() / 2;
            final int y = (getHeight() - dialogGeneralSeach.getHeight());
            dialogGeneralSeach.setLocation(x, y);
            dialogGeneralSeach.setButtonOKClickedListenner(new MyEventListener() {
                @Override
                public void myEventOccured(Object evt) {
                    setSelectedKhachHang((NguoiDung) evt);
                }
            });
            dialogGeneralSeach.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnSearchKhachHangActionPerformed

    private void btnThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThoatActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnThoatActionPerformed

    private void txtMaKhachHangFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaKhachHangFocusLost
        // TODO add your handling code here:
        try {
            if (!txtMaKhachHang.getText().isEmpty()) {
                if (selectedKhachHang == null || Integer.parseInt(txtMaKhachHang.getText()) != selectedKhachHang.getId()) {
                    NguoiDung nguoiDung = (NguoiDung) NguoiDungDAO.LayTheoID(NguoiDung.class, Integer.parseInt(txtMaKhachHang.getText()));
                    if (nguoiDung == null) {
                        JOptionPane.showMessageDialog(this, "Không tìm thấy mã này trong hệ thống");
                    }
                    setSelectedKhachHang(nguoiDung);
                }
            } else {
                setSelectedKhachHang(null);
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_txtMaKhachHangFocusLost

    private void btnSearchSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchSanPhamActionPerformed
        try {
            // TODO add your handling code here:
            DialogGeneralSeach dialogGeneralSeach = new DialogGeneralSeach(null, true, SearchGeneralEnum.SanPhamCuaHang);
            final int x = (getWidth() - dialogGeneralSeach.getWidth()) + getX() / 2;
            final int y = (getHeight() - dialogGeneralSeach.getHeight());
            dialogGeneralSeach.setLocation(x, y);
            dialogGeneralSeach.setButtonOKClickedListenner(new MyEventListener() {
                @Override
                public void myEventOccured(Object evt) {
                    setSelectedSanPhamCuaHang((SanPhamCuaHang) evt);
                }
            });
            dialogGeneralSeach.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnSearchSanPhamActionPerformed

    private void txtMaSanPhamCuaHangFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaSanPhamCuaHangFocusLost
        // TODO add your handling code here:
        try {
            if (!txtMaSanPhamCuaHang.getText().isEmpty()) {
                if (selectedSanPhamCuaHang == null || Integer.parseInt(txtMaSanPhamCuaHang.getText()) != selectedSanPhamCuaHang.getId()) {
                    SanPhamCuaHang sanPhamCuaHang = SanPhamCuaHangDAO.LayTheoID(Integer.parseInt(txtMaSanPhamCuaHang.getText()), MainGUI.nguoiDung);
                    if (sanPhamCuaHang == null) {
                        JOptionPane.showMessageDialog(this, "Không tìm thấy mã sản phẩm cửa hàng này trong hệ thống");
                    }
                    setSelectedSanPhamCuaHang(sanPhamCuaHang);
                }
            } else {
                setSelectedSanPhamCuaHang(null);
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_txtMaSanPhamCuaHangFocusLost

    private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
        // TODO add your handling code here:
        if (CheckDataBeforeThem() > 0) {
            return;
        }
        ChiTietHoaDon chiTietHoaDon = null;
        for (ChiTietHoaDon cthd : chiTietHoaDons) {
            if (cthd.getSanPhamCuaHang().getId() == selectedSanPhamCuaHang.getId()) {
                chiTietHoaDon = cthd;
                break;
            }
        }
        if (chiTietHoaDon == null) {
            chiTietHoaDon = new ChiTietHoaDon(0, hoaDon, selectedSanPhamCuaHang, (Double) txtDonGia.getValue(), Integer.parseInt(txtSoLuongDat.getText()), false, (Double) txtTongTienChiTiet.getValue(), false, null);
            chiTietHoaDons.add(chiTietHoaDon);
        } else {
            chiTietHoaDon.setSoLuong(chiTietHoaDon.getSoLuong() + Integer.parseInt(txtSoLuongDat.getText()));
            chiTietHoaDon.setTongTien(chiTietHoaDon.getTongTien() + (Double) txtTongTienChiTiet.getValue());
        }
        Utility.CreateColumnsFromDB(ChiTietHoaDon.class, chiTietHoaDons, tbChiTietHoaDon, new String[]{"Mã sản phẩm cửa hàng", "Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Đã thanh toán"}, new String[]{"id", "idHoaDon"});
        CalculateTongTien();
    }//GEN-LAST:event_btnThemActionPerformed

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        // TODO add your handling code here:
        Utility.ClearControlInPanel(jPanel1);
        setSelectedSanPhamCuaHang(null);
    }//GEN-LAST:event_btnClearActionPerformed

    private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
        // TODO add your handling code here:
        List<ChiTietHoaDon> tempList = (List<ChiTietHoaDon>) Utility.GetSelectedRows(tbChiTietHoaDon, chiTietHoaDons);
        if (!tempList.isEmpty()) {
            for (ChiTietHoaDon chiTietHoaDon : tempList) {
                if (chiTietHoaDon.getDaThanhToan().equals(true)) {
                    JOptionPane.showMessageDialog(this, "Có chi tiết hoá đơn đã thanh toán được chọn nên không thể xoá");
                    return;
                }
            }
            if (JOptionPane.showConfirmDialog(this, "Bạn có chắc muốn xoá không?", "Question", JOptionPane.YES_NO_OPTION) == 0) {
                Utility.RemoveSelectedRows(ChiTietHoaDon.class, tbChiTietHoaDon, chiTietHoaDons, new String[]{"Mã sản phẩm cửa hàng", "Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Đã thanh toán"}, new String[]{"id", "idHoaDon"});
                CalculateTongTien();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để xoá");
        }
    }//GEN-LAST:event_btnXoaActionPerformed

    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
        try {
            // TODO add your handling code here:
            if (CheckDataBeforeLuu() > 0) {
                return;
            }
            if (hoaDon.getId() == 0) {
                if (ButtonLuuClickedListener == null) {
                    return;
                }
                hoaDon = new HoaDon(0, trangThaiDonHangs.get(2), selectedKhachHang, MainGUI.nguoiDung.getCuaHang(), dtNgayLapHoaDon.getDate(), (Double) txtTongTien.getValue(), false, null);
                Integer id = HoaDonDAO.Them(hoaDon, chiTietHoaDons);
                hoaDon.setId(id);
                JOptionPane.showMessageDialog(this, "Lập hoá đơn thành công");
                ButtonLuuClickedListener.myEventOccured(hoaDon);
            } else {
                int demThanhToan = 0;
                for (ChiTietHoaDon chiTietHoaDon : chiTietHoaDons) {
                    if (chiTietHoaDon.getDaThanhToan()) {
                        demThanhToan++;
                    }
                }
                if (demThanhToan == 0) {
                    hoaDon.setTrangThaiDonHang(trangThaiDonHangs.get(2));
                } else if (demThanhToan < chiTietHoaDons.size()) {
                    hoaDon.setTrangThaiDonHang(trangThaiDonHangs.get(1));
                } else {
                    hoaDon.setTrangThaiDonHang(trangThaiDonHangs.get(0));
                }
                hoaDon.setTongTien((Double) txtTongTien.getValue());
                HoaDonDAO.Sua(hoaDon, chiTietHoaDons);
                JOptionPane.showMessageDialog(this, "Cập nhật hoá đơn thành công");
            }
            dispose();
        } catch (Exception ex) {
            hoaDon.setTongTien(oldHoaDon.getTongTien());
            hoaDon.setTrangThaiDonHang(oldHoaDon.getTrangThaiDonHang());
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnLuuActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnSearchKhachHang;
    private javax.swing.JButton btnSearchSanPham;
    private javax.swing.JButton btnThem;
    private javax.swing.JButton btnThoat;
    private javax.swing.JButton btnXoa;
    private org.jdesktop.swingx.JXDatePicker dtNgayLapHoaDon;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable tbChiTietHoaDon;
    private javax.swing.JFormattedTextField txtDonGia;
    private javax.swing.JTextField txtMaKhachHang;
    private javax.swing.JTextField txtMaSanPhamCuaHang;
    private javax.swing.JTextField txtSoLuongDat;
    private javax.swing.JTextField txtSoLuongTon;
    private javax.swing.JTextField txtTenKhachHang;
    private javax.swing.JTextField txtTenSanPham;
    private javax.swing.JFormattedTextField txtTongTien;
    private javax.swing.JFormattedTextField txtTongTienChiTiet;
    // End of variables declaration//GEN-END:variables

    /**
     * @param selectedKhachHang the selectedKhachHang to set
     */
    public void setSelectedKhachHang(NguoiDung selectedKhachHang) {
        this.selectedKhachHang = selectedKhachHang;
        if (selectedKhachHang != null) {
            txtMaKhachHang.setText(String.valueOf(selectedKhachHang.getId()));
            txtTenKhachHang.setText(selectedKhachHang.getTenNguoiDung());
        } else {
            txtMaKhachHang.setText(null);
            txtTenKhachHang.setText(null);
        }
    }

    /**
     * @param selectedSanPham the selectedSanPham to set
     */
    public void setSelectedSanPhamCuaHang(SanPhamCuaHang selectedSanPhamCuaHang) {
        this.selectedSanPhamCuaHang = selectedSanPhamCuaHang;
        txtSoLuongDat.setText(null);
        if (selectedSanPhamCuaHang != null) {
            txtMaSanPhamCuaHang.setText(String.valueOf(selectedSanPhamCuaHang.getId()));
            txtTenSanPham.setText(selectedSanPhamCuaHang.getSanPham().getTenSanPham());
            txtDonGia.setValue(selectedSanPhamCuaHang.getSanPham().getDonGia());
            txtSoLuongTon.setText(String.valueOf(selectedSanPhamCuaHang.getSoLuong()));
        } else {
            txtMaSanPhamCuaHang.setText(null);
            txtTenSanPham.setText(null);
            txtDonGia.setValue(null);
            txtSoLuongTon.setText(null);
        }
    }

    /**
     * @param ButtonLuuClickedListener the ButtonLuuClickedListener to set
     */
    public void setButtonLuuClickedListener(MyEventListener ButtonLuuClickedListener) {
        this.ButtonLuuClickedListener = ButtonLuuClickedListener;
    }
}
